package com.ad.aidai.activitys.login;

import android.content.Context;
import android.content.SharedPreferences;

import com.ad.aidai.bean.UserWithSchool;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.common.utils.EncryptUtils;
import com.ad.aidai.db.dao.MyUserDao;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.LoginResultFromNet;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static android.content.Context.MODE_PRIVATE;

/**
 * LoginPresenter
 * <p>
 * Created by Yusxon on 16/11/27.
 */

public class LoginPresenter implements LoginContract.Presenter {

    private Context mContext;
    private LoginContract.View mView;
    private CompositeSubscription mSubscriptions;
    private SharedPreferences aidaiSP;

    public LoginPresenter(Context context, LoginContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        aidaiSP = mContext.getSharedPreferences("AIDAI", MODE_PRIVATE);
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
    }
    private String passwordMD5;

    @Override
    public void login(final String phoneNumber, final String password) {
        if (CheckUtil.checkStrNull(phoneNumber) || CheckUtil.checkStrNull(password)) {
            mView.toast("手机号和密码不能为空");
        } else if (!CheckUtil.checkPhone(phoneNumber)) {
            mView.toast("手机号格式不正确");
        } else {
            //显示加载对话框
            mView.showLoading();
            passwordMD5 = EncryptUtils.GetMD5Code(password);
            NetWork.getAccountOperationApi()
                    .login(phoneNumber, passwordMD5)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<LoginResultFromNet>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            MobclickAgent.reportError(mContext, e);
                            Logger.t("LoginPresenter").e(e.getMessage());
                            //关闭加载对话框
                            mView.closeLoading(false);
                        }

                        @Override
                        public void onNext(LoginResultFromNet loginResultFromNet) {

//                            Logger.t("LoginPresenter").i(loginResultFromNet.toString());
                            if (loginResultFromNet.getCode() != StatusCodeFromNet.CODE_SUCCESS) {
                                mView.closeLoading(false);
                                dealErrorCode(loginResultFromNet.getCode());
                            } else {
                                UserWithSchool user = loginResultFromNet.getData();
                                user.setSchoolName();
//                                Logger.t("LoginPresenter").i(user.toString());
                                MyUserDao.getUserDao().deleteAll();
                                MyUserDao.getUserDao().insert(user);
                                ADApp.setUser();
                                savePhoneAndPwd(phoneNumber, passwordMD5);
                                mView.closeLoading(true);
                                mView.loginSuccess();
                            }
                        }
                    });
        }
    }

    @Override
    public void loadPhone() {
        mView.setPhoneNumber(aidaiSP.getString("USER_PHONE", ""));
    }

    /**
     * 保存用户手机号跟密码,以便下次登录自动加载到输入框中
     *
     * @param phone    手机号
     * @param password 密码
     */
    private void savePhoneAndPwd(String phone, String password) {
        aidaiSP.edit()
                .putBoolean("IS_LOGIN", true)
                .putString("USER_PHONE", phone)
                .putString("USER_PASSWORD", password)
                .apply();
    }

    /**
     * 处理错误码信息
     *
     * @param code 错误码
     */
    private void dealErrorCode(int code) {
        switch (code) {
            case StatusCodeFromNet.CODE_PHONE_ERROR:
            case StatusCodeFromNet.CODE_PASSWORD_ERROR:
                mView.toast("手机号或密码错误");
                break;
            case StatusCodeFromNet.CODE_SERVER_EXCEPTION:
                mView.toast("服务器异常");
                break;
            default:
                break;
        }
    }
}
